package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/add")
    public User add(User user){
        return user;
    }

    @RequestMapping("/name")
    public String name(@RequestParam (value="n",required = false) String name){
        return name;
    }
    @RequestMapping("/add_json")
    public User addByJson(@RequestBody User user){
        return user;
    }
    @RequestMapping("/detial/{id}/{name}")
    public String detail(@PathVariable("id") Integer id,@PathVariable("name") String name){
        return "id: "+id+" "+"name: "+name;
    }
    @RequestMapping("/upload")
    public String upload(@RequestPart("myfile") MultipartFile file) throws IOException {
        //1、生成一个唯一的id(UUID就是全球唯一ID，他是由MAC地址+随机数+加密算法组成的，保证生成的id是全球唯一ID)
        String name = UUID.randomUUID().toString().replace("-","");
        //2、得到源文件的后缀名
        name += file.getOriginalFilename().
                substring(file.getOriginalFilename().lastIndexOf("."));
        String path = "D:/"+name;
        //将文件保存在path路径中
        file.transferTo(new File(path));
        return path;
    }
    @RequestMapping("/getcookie")
    public String getCookie(@CookieValue("java")String ck){
        return ck;
    }
    @RequestMapping("/sess1")
    public String sess1(HttpServletRequest req) {
        // 如果 session 不存在, 不会自动创建
        HttpSession session = req.getSession(false);
        String username = "张三";
        if (session != null && session.getAttribute("username") != null) {
            username = (String) session.getAttribute("username");
        }
        return username;
    }

    @RequestMapping("/getsess")
    public String getSess(@SessionAttribute(value="username",required = false) String username){
        return username;
    }
}
